using UnityEngine;
using UnityEngine.UI;
using TMPro;

namespace Emerald4
{
    /// <summary>
    /// Simple, clean system for adding custom apps to Somnium Space tablet.
    /// Just attach this to a GameObject, assign your app prefab, and configure the button settings.
    /// </summary>
    public class SomniumTabletApp : MonoBehaviour
    {
        [Header("App Settings")]
        [Tooltip("Your custom app UI (will be spawned when button is clicked)")]
        public GameObject appPrefab;

        [Tooltip("Icon for the tablet menu button")]
        public Sprite buttonIcon;

        [Tooltip("Title text for the tablet menu button")]
        public string buttonTitle = "My App";

        [Header("Display Settings")]
        [Tooltip("Auto-resize tablet when app opens")]
        public bool autoResizeOnOpen = true;

        [Tooltip("Position offset to apply to the app UI (use to fine-tune positioning)")]
        public Vector3 positionOffset = Vector3.zero;

        [Header("Debug")]
        public bool showDebugLogs = false;

        // Internal tablet paths (hidden from inspector - don't change unless Somnium updates)
        [HideInInspector] public string[] tabletKeywords = { "Tablet.XR(Clone)", "Tablet.NonXR(Clone)" };
        [HideInInspector] public string homeButtonContainerPath = "Canvases/Tablet.XR.Tabs/Tablet.XR.HomeTab/ContentView";
        [HideInInspector] public string referenceButtonName = "Tablet.XR.SwitchTabBtn - My Avatar";
        [HideInInspector] public string applicationsPath = "Canvases/Tablet.XR.Tabs";
        [HideInInspector] public string backButtonPath = "Canvases/Tablet.XR.StatusBar/StatusBar/LeftSideGroup/Tablet.XR.StatusBar.Back";
        [HideInInspector] public string resizeButtonPath = "Canvases/Tablet.XR.StatusBar/StatusBar/Btns/Tablet.XR.StatusBar.CapabilityBtn - Resize";

        // Runtime references
        private GameObject _tablet;
        private GameObject _menuButton;
        private GameObject _appInstance;
        private GameObject _originalAppsRoot;
        private GameObject _customAppsRoot;
        private Button _backButton;
        private Button _resizeButton;

        private void Start()
        {
            StartCoroutine(InitializeTabletApp());
        }

        private System.Collections.IEnumerator InitializeTabletApp()
        {
            // Step 1: Find the tablet
            yield return FindTablet();

            if (_tablet == null)
            {
                Debug.LogError("[SomniumTabletApp] Failed to find tablet. Make sure you're in Somnium Space!");
                yield break;
            }

            // Step 2: Set up the custom apps container
            SetupCustomAppsContainer();

            // Step 3: Create the menu button
            CreateMenuButton();

            // Step 4: Set up back button
            SetupBackButton();

            // Step 5: Set up resize button
            SetupResizeButton();

            if (showDebugLogs)
                Debug.Log($"[SomniumTabletApp] ✓ '{buttonTitle}' app initialized successfully!");
        }

        /// <summary>
        /// Search all scenes for the Somnium tablet
        /// </summary>
        private System.Collections.IEnumerator FindTablet()
        {
            int attempts = 0;
            while (_tablet == null && attempts < 30)
            {
                attempts++;

                if (showDebugLogs && attempts % 5 == 0)
                    Debug.Log($"[SomniumTabletApp] Searching for tablet... (attempt {attempts}/30)");

                // The tablet is parented under the local player rig, not at scene root,
                // so this has to walk every transform rather than GetRootGameObjects().
                foreach (var candidate in Resources.FindObjectsOfTypeAll<Transform>())
                {
                    if (candidate.hideFlags != HideFlags.None) continue;
                    if (!candidate.gameObject.scene.IsValid()) continue;

                    foreach (var keyword in tabletKeywords)
                    {
                        if (candidate.name.Contains(keyword))
                        {
                            _tablet = candidate.gameObject;
                            if (showDebugLogs)
                                Debug.Log($"[SomniumTabletApp] ✓ Found tablet: {_tablet.name}");
                            yield break;
                        }
                    }
                }

                yield return new WaitForSeconds(1f);
            }

            if (_tablet == null)
                Debug.LogError("[SomniumTabletApp] Tablet not found after 30 attempts!");
        }

        /// <summary>
        /// Create a custom applications container (clone of the original)
        /// </summary>
        private void SetupCustomAppsContainer()
        {
            Transform appsTransform = _tablet.transform.Find(applicationsPath);
            if (appsTransform == null)
            {
                Debug.LogError($"[SomniumTabletApp] Could not find applications path: {applicationsPath}");
                return;
            }

            _originalAppsRoot = appsTransform.gameObject;

            // Clone the applications root
            _customAppsRoot = Instantiate(_originalAppsRoot, _originalAppsRoot.transform.parent);
            _customAppsRoot.name = "CustomApps_" + buttonTitle;
            _customAppsRoot.SetActive(false);

            // Clear all children
            foreach (Transform child in _customAppsRoot.transform)
            {
                Destroy(child.gameObject);
            }

            // Spawn your custom app
            if (appPrefab != null)
            {
                _appInstance = Instantiate(appPrefab, _customAppsRoot.transform);
                _appInstance.SetActive(true);

                // Apply position offset if specified
                if (positionOffset != Vector3.zero)
                {
                    var rectTransform = _appInstance.GetComponent<RectTransform>();
                    if (rectTransform != null)
                    {
                        rectTransform.anchoredPosition += new Vector2(positionOffset.x, positionOffset.y);
                        rectTransform.localPosition = new Vector3(
                            rectTransform.localPosition.x,
                            rectTransform.localPosition.y,
                            rectTransform.localPosition.z + positionOffset.z
                        );
                        if (showDebugLogs)
                            Debug.Log($"[SomniumTabletApp] Applied position offset: {positionOffset}");
                    }
                }

                if (showDebugLogs)
                    Debug.Log($"[SomniumTabletApp] ✓ Custom app spawned: {appPrefab.name}");
            }
            else
            {
                Debug.LogWarning("[SomniumTabletApp] No app prefab assigned!");
            }
        }

        /// <summary>
        /// Create a menu button by cloning an existing button
        /// </summary>
        private void CreateMenuButton()
        {
            // Find the container with home buttons
            Transform containerTransform = _tablet.transform.Find(homeButtonContainerPath);
            if (containerTransform == null)
            {
                Debug.LogError($"[SomniumTabletApp] Could not find home button container: {homeButtonContainerPath}");
                return;
            }

            // Find a reference button to clone
            Transform referenceButton = containerTransform.Find(referenceButtonName);
            if (referenceButton == null)
            {
                Debug.LogError($"[SomniumTabletApp] Could not find reference button: {referenceButtonName}");
                return;
            }

            // Clone the button
            _menuButton = Instantiate(referenceButton.gameObject, containerTransform);
            _menuButton.name = "CustomBtn_" + buttonTitle;

            // Remove any custom scripts (keep only Unity built-ins)
            StripNonUnityScripts(_menuButton);

            // Update button visuals
            UpdateButtonVisuals(_menuButton);

            // Hook up button click
            var button = _menuButton.GetComponent<Button>();
            if (button != null)
            {
                button.onClick.RemoveAllListeners();
                button.onClick.AddListener(OpenApp);
                button.interactable = true;
            }

            _menuButton.SetActive(true);

            if (showDebugLogs)
                Debug.Log($"[SomniumTabletApp] ✓ Menu button created: {buttonTitle}");
        }

        /// <summary>
        /// Update button icon and text
        /// </summary>
        private void UpdateButtonVisuals(GameObject button)
        {
            // Update icon
            Transform iconTransform = button.transform.Find("Icon");
            if (iconTransform != null && buttonIcon != null)
            {
                var iconImage = iconTransform.GetComponent<Image>();
                if (iconImage != null)
                    iconImage.sprite = buttonIcon;
            }

            // Update title
            Transform titleTransform = button.transform.Find("Text");
            if (titleTransform != null)
            {
                var titleText = titleTransform.GetComponent<TextMeshProUGUI>();
                if (titleText != null)
                    titleText.text = buttonTitle;
            }
        }

        /// <summary>
        /// Set up the back/home button to close your app
        /// </summary>
        private void SetupBackButton()
        {
            Transform backTransform = _tablet.transform.Find(backButtonPath);
            if (backTransform != null)
            {
                _backButton = backTransform.GetComponent<Button>();
                if (_backButton != null)
                {
                    _backButton.onClick.AddListener(CloseApp);
                }
            }
            else
            {
                Debug.LogWarning($"[SomniumTabletApp] Could not find back button: {backButtonPath}");
            }
        }

        /// <summary>
        /// Set up the resize button reference
        /// </summary>
        private void SetupResizeButton()
        {
            Transform resizeTransform = _tablet.transform.Find(resizeButtonPath);
            if (resizeTransform != null)
            {
                _resizeButton = resizeTransform.GetComponent<Button>();

                if (showDebugLogs && _resizeButton != null)
                    Debug.Log($"[SomniumTabletApp] ✓ Resize button found");
            }
            else
            {
                Debug.LogWarning($"[SomniumTabletApp] Could not find resize button: {resizeButtonPath}");
            }
        }

        /// <summary>
        /// Remove all non-Unity scripts from a GameObject
        /// </summary>
        private void StripNonUnityScripts(GameObject obj)
        {
            var behaviours = obj.GetComponentsInChildren<MonoBehaviour>(true);
            foreach (var mb in behaviours)
            {
                if (mb == null) continue;

                var type = mb.GetType();
                var ns = type.Namespace ?? string.Empty;

                // Keep Unity and TMPro built-ins
                if (ns.StartsWith("UnityEngine") || ns.StartsWith("TMPro"))
                    continue;

                // Destroy custom scripts
                Destroy(mb);
            }
        }

        /// <summary>
        /// Open your custom app
        /// </summary>
        public void OpenApp()
        {
            if (_originalAppsRoot == null || _customAppsRoot == null) return;

            _originalAppsRoot.SetActive(false);
            _customAppsRoot.SetActive(true);

            // Enable back button when app opens
            if (_backButton != null)
            {
                _backButton.gameObject.SetActive(true);
            }

            // Auto-resize tablet if enabled
            if (autoResizeOnOpen && _resizeButton != null)
            {
                _resizeButton.onClick.Invoke();

                if (showDebugLogs)
                    Debug.Log($"[SomniumTabletApp] Triggered resize");
            }

            if (showDebugLogs)
                Debug.Log($"[SomniumTabletApp] Opened: {buttonTitle}");
        }

        /// <summary>
        /// Close your app and return to home
        /// </summary>
        public void CloseApp()
        {
            if (_originalAppsRoot == null || _customAppsRoot == null) return;

            _customAppsRoot.SetActive(false);
            _originalAppsRoot.SetActive(true);

            // Disable back button when returning to home
            if (_backButton != null)
            {
                _backButton.gameObject.SetActive(false);
            }

            // Trigger resize again to return to default size
            if (autoResizeOnOpen && _resizeButton != null)
            {
                _resizeButton.onClick.Invoke();

                if (showDebugLogs)
                    Debug.Log($"[SomniumTabletApp] Triggered resize back to default");
            }

            if (showDebugLogs)
                Debug.Log($"[SomniumTabletApp] Closed: {buttonTitle}");
        }

        private void OnDestroy()
        {
            // Clean up button listener
            if (_backButton != null)
            {
                _backButton.onClick.RemoveListener(CloseApp);
            }
        }
    }
}
